import { ref } from 'vue'
import axios from 'axios'

export default function useFileUpload(options = {}) {
  // 默认配置
  const defaultConfig = {
    endpoint: '/upload',  // 上传接口
    fieldName: 'file',    // 文件字段名
    maxSize: 5 * 1024 * 1024, // 默认5MB
    allowedTypes: ['image/*'], // 允许的文件类型
    extraData: {}         // 额外携带的数据
  }

  // 合并配置
  const config = { ...defaultConfig, ...options }

  // 响应式状态
  const isUploading = ref(false)
  const uploadResult = ref(null)
  const error = ref(null)
  const progress = ref(0) // 上传进度

  // 执行上传的方法
  const upload = async (file) => {
    // 重置状态
    isUploading.value = true
    error.value = null
    uploadResult.value = null
    progress.value = 0

    try {
      // 文件校验
      if (!file) throw new Error('请选择文件')
      if (!config.allowedTypes.some(t => new RegExp(t.replace('*', '.*')).test(file.type))) {
        throw new Error('不支持的文件类型')
      }
      if (file.size > config.maxSize) {
        throw new Error(`文件大小不能超过${config.maxSize/1024/1024}MB`)
      }

      // 构建表单数据
      const formData = new FormData()
      formData.append(config.fieldName, file)

      // 添加额外数据
      Object.entries(config.extraData).forEach(([key, value]) => {
        formData.append(key, value)
      })

      // 发送请求
      const response = await axios.post(config.endpoint, formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        onUploadProgress: (progressEvent) => {
          progress.value = Math.round(
            (progressEvent.loaded * 100) / progressEvent.total
          )
        }
      })
      // 处理响应
      if (response.data.code === 1) {
        uploadResult.value = response.data.data
        return response.data.data
      } else {
        throw new Error(response.data.msg || '上传失败')
      }
    } catch (err) {
      error.value = err.message || '上传失败'
      throw err
    } finally {
      isUploading.value = false
    }
  }

  return {
    upload,
    isUploading,
    uploadResult,
    error,
    progress
  }
}
